package main

import (
	"context"
	blobpb "coolcar/proto/blob_out/v1"
	"coolcar/srvs/blob_srv/dao"
	"coolcar/srvs/blob_srv/handler"
	"coolcar/srvs/blob_srv/storage"
	"log"
	"net"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"

	"google.golang.org/grpc"
)

func main() {
	logger, err := newZapLogger()
	if err != nil {
		log.Fatalf("can not create logger: %v", err)
	}

	listener, err := net.Listen("tcp", ":50091")
	if err != nil {
		logger.Fatal("failed to listen: %v \n", zap.Error(err))
	}

	// 初始化Mongo
	mongoClient, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017/coolcar?readPreference=primary&appname=mongodb-vscode%200.7.0&directConnection=true&ssl=false"))
	if err != nil {
		logger.Fatal("can not connect mongodb: %v", zap.Error(err))
	}
	mongoDB := dao.NewMongo(mongoClient.Database("coolcar"))

	sto := storage.NewCOS(
		"https://coolcar-1305922819.cos.ap-guangzhou.myqcloud.com",
		"AKIDFI5csqXyB9rJUNzKPEn57rLZWEgsoTry",
		"rTpwmLkxvkNlulMfhSwDEyRdYCZgaFdk",
	)

	s := grpc.NewServer()
	blobpb.RegisterBlobServiceServer(s, &handler.Service{
		Mongo:   mongoDB,
		Logger:  logger,
		Storage: &sto,
	})

	log.Fatal(s.Serve(listener))
}

func newZapLogger() (*zap.Logger, error) {
	cfg := zap.NewDevelopmentConfig()
	cfg.EncoderConfig.TimeKey = ""
	return cfg.Build()
}
